package com.dcrzl.gazgmh.common.interceptor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dcrzl.gazgmh.common.entity.sys.SysConfig;
import com.dcrzl.gazgmh.common.enums.UserTypeEnum;
import com.dcrzl.gazgmh.common.utils.JwtUtils;
import com.dcrzl.gazgmh.common.utils.Result;
import com.dcrzl.gazgmh.common.utils.SysConstant;
import com.dcrzl.gazgmh.common.utils.UserInfoByTokenUtils;
import com.dcrzl.gazgmh.module.sys.service.SysConfigService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json");
        String token = request.getHeader("token");
        log.info(token);
        if (StringUtils.isEmpty(token)) {
            Result Result = new Result();
            Result.setSuccess(false).setMsg("token不能为空").setCode(SysConstant.NOT_LOGIN_RES_CODE);
            String jsonStr = JSON.toJSONString(Result);
            log.info(jsonStr);
            response.getWriter().println(jsonStr);
            return false;
        } else {
            Result Result = JwtUtils.parseJwt(token);
            if (Result.isSuccess()) {
                Claims claims = (Claims) Result.getData();
                //验证会话
                JSONObject jsonObject = UserInfoByTokenUtils.parseJson(request);
                String key = jsonObject.getLong("userId")+":"+jsonObject.getString("userType");
                if(Objects.nonNull(stringRedisTemplate.opsForValue().get(key))){
                    //设置会话时间
                    Result<SysConfig> sysConfigResult = sysConfigService.selectOne(new SysConfig().setStatus(SysConstant.DATA_NORMAL_STATUS));
                    int time = 30;
                    if(sysConfigResult.isSuccess()){
                        SysConfig sysConfig = sysConfigResult.getData();
                        time = sysConfig.getSessionTime();
                    }
                    stringRedisTemplate.opsForValue().set(key,
                            jsonObject.getLong("userId")+"",time, TimeUnit.MINUTES);
                }else{
                    String s = JSON.toJSONString(new Result<>().setSuccess(false).setCode(SysConstant.RES_JWT_PARSE_ERROR).setMsg("会话过期"));
                    response.getWriter().println(s);
                    return false;
                }

                String uri = request.getRequestURI();
                log.info(uri);
                //权限验证
                Result result  = this.checkPerms(claims,uri);
                boolean isPerms = result.isSuccess();
                if (isPerms) {
                    return true;
                } else {
                    String s = JSON.toJSONString(result);
                    response.getWriter().println(s);
                    return false;
                }
            } else {
                response.getWriter().println(JSON.toJSONString(Result));
                return false;
            }
        }
    }

    /**
     * 检查该角色是否拥有该权限
     *
     * @param uri      请求URI
     * @return
     */
    private Result checkPerms(Claims claims,String uri) {
        Integer userType = claims.get("userType", Integer.class);
        Long roleId = claims.get("roleId", Long.class);
        return new Result().setSuccess(true);
//        if(userType==SysConstant.WX_MINI_SHOP_TYPE){
//            if(!uri.matches("/shop.((?!console).)*")){
//                return new Result().setSuccess(false).setCode(SysConstant.PARAM_LACK_CODE_RES).setMsg("请求接口错误");
//            }
//            return new Result().setSuccess(true);
//        }else if (userType==SysConstant.WX_MINI_USER_TYPE) {
//            if(!uri.matches("/buyer.*")){
//                return new Result().setSuccess(false).setCode(SysConstant.PARAM_LACK_CODE_RES).setMsg("请求接口错误");
//            }
//            return new Result().setSuccess(true);
//        }else if (Objects.equals(roleId, SysConstant.ROOT_ID)) {
//            if(!uri.matches("/shop/console.*")){
//                return new Result().setSuccess(false).setCode(SysConstant.PARAM_LACK_CODE_RES).setMsg("请求接口错误");
//            }
//            return new Result().setSuccess(true);
//        }
//        return new Result().setSuccess(false).setCode(SysConstant.PERMS_LACK_CODE_RES).setMsg("权限缺失");

    }

}
